/*
 * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: Apache-2.0
 */

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/queue.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "esp_log.h"
#include "esp_sntp.h"
#include "esp_netif.h"
#include "nvs_flash.h"
#include "driver/gpio.h"
// 移除I2C相关头文件，不再需要OLED显示
#include "iot_button.h"
#include "led_indicator.h"
#include "board_common.h"
#include "ds1302.h"
#include "at_chat.h"
#include "web_server.h"

#include "esp_bridge.h"
#if defined(CONFIG_APP_BRIDGE_USE_WEB_SERVER)
#include "web_server.h"
#endif
#include "iot_button.h"
#if defined(CONFIG_APP_BRIDGE_USE_WIFI_PROVISIONING_OVER_BLE)
#include "wifi_prov_mgr.h"
#endif

#include "ds1302.h"
#include "esp_netif_sntp.h"
#include "lwip/ip_addr.h"
#include "esp_sntp.h"

#include "iot_board.h"
#include "led_ledc.h"
#include "esp_at.h"
#include "led_indicator.h"
#include "led_indicator_gpio.h"

#ifndef INET6_ADDRSTRLEN
#define INET6_ADDRSTRLEN 48
#endif

static const char *TAG = "main";

// 3个DS1302设备描述符（使用 esp-idf-lib ds1302 驱动）
static ds1302_t ds1302_dev[3];

// 校时状态枚举
typedef enum {
    SYNC_STATUS_IDLE = 0,      // 空闲状态
    SYNC_STATUS_SYNCING,       // 校时进行中
    SYNC_STATUS_SUCCESS,        // 校时成功
    SYNC_STATUS_FAILED         // 校时失败
} sync_status_t;

static sync_status_t sync_status = SYNC_STATUS_IDLE;
static bool sync_in_progress = false;

// 任务相关定义
#define SYNC_TASK_STACK_SIZE 4096
#define SYNC_TASK_PRIORITY 5
static TaskHandle_t sync_task_handle = NULL;
static QueueHandle_t sync_queue = NULL;

// 校时任务消息结构
typedef struct {
    bool trigger_sync;
} sync_task_msg_t;

// LED指示器句柄
static led_indicator_handle_t led_handle = NULL;        // 主LED - WiFi和NTP状态
static led_indicator_handle_t led_handle_2 = NULL;      // LED2 - DS1302芯片1状态
static led_indicator_handle_t led_handle_3 = NULL;      // LED3 - DS1302芯片2状态
static led_indicator_handle_t led_handle_4 = NULL;      // LED4 - DS1302芯片3状态

// 定义闪烁模式
enum {
    BLINK_WIFI_CONNECTING = 0,    // WiFi连接中 - 慢闪
    BLINK_WIFI_CONNECTED,         // WiFi已连接 - 快闪
    BLINK_NTP_SYNCING,            // NTP同步中 - 双闪
    BLINK_NTP_SYNC_DONE,          // NTP同步完成 - 常亮1秒
    BLINK_CHIP_SYNC_START,        // 单个芯片校时开始 - 熄灭
    BLINK_CHIP_SUCCESS,           // 单个芯片成功 - 常亮
    BLINK_CHIP_FAILED,            // 单个芯片失败 - 快闪
    BLINK_MAX,
};

// WiFi连接中 - 慢闪
static const blink_step_t wifi_connecting_blink[] = {
    {LED_BLINK_HOLD, LED_STATE_ON, 500},
    {LED_BLINK_HOLD, LED_STATE_OFF, 500},
    {LED_BLINK_LOOP, 0, 0},
};

// WiFi已连接 - 快闪
static const blink_step_t wifi_connected_blink[] = {
    {LED_BLINK_HOLD, LED_STATE_ON, 200},
    {LED_BLINK_HOLD, LED_STATE_OFF, 200},
    {LED_BLINK_LOOP, 0, 0},
};

// NTP同步中 - 双闪
static const blink_step_t ntp_syncing_blink[] = {
    {LED_BLINK_HOLD, LED_STATE_ON, 100},
    {LED_BLINK_HOLD, LED_STATE_OFF, 100},
    {LED_BLINK_HOLD, LED_STATE_ON, 100},
    {LED_BLINK_HOLD, LED_STATE_OFF, 300},
    {LED_BLINK_LOOP, 0, 0},
};

// NTP同步完成 - 常亮1秒
static const blink_step_t ntp_sync_done_blink[] = {
    {LED_BLINK_HOLD, LED_STATE_ON, 1000},
    {LED_BLINK_HOLD, LED_STATE_OFF, 0},
    {LED_BLINK_STOP, 0, 0},
};


// 单个芯片校时开始 - 熄灭
static const blink_step_t chip_sync_start_blink[] = {
    {LED_BLINK_HOLD, LED_STATE_OFF, 0},
    {LED_BLINK_STOP, 0, 0},
};

// 单个芯片成功 - 常亮
static const blink_step_t chip_success_blink[] = {
    {LED_BLINK_HOLD, LED_STATE_ON, 0},
    {LED_BLINK_STOP, 0, 0},
};

// 单个芯片失败 - 快闪
static const blink_step_t chip_failed_blink[] = {
    {LED_BLINK_HOLD, LED_STATE_ON, 100},
    {LED_BLINK_HOLD, LED_STATE_OFF, 100},
    {LED_BLINK_LOOP, 0, 0},
};

// LED模式数组
blink_step_t const *led_mode[] = {
    [BLINK_WIFI_CONNECTING] = wifi_connecting_blink,
    [BLINK_WIFI_CONNECTED] = wifi_connected_blink,
    [BLINK_NTP_SYNCING] = ntp_syncing_blink,
    [BLINK_NTP_SYNC_DONE] = ntp_sync_done_blink,
    [BLINK_CHIP_SYNC_START] = chip_sync_start_blink,
    [BLINK_CHIP_SUCCESS] = chip_success_blink,
    [BLINK_CHIP_FAILED] = chip_failed_blink,
    [BLINK_MAX] = NULL,
};

void time_sync_notification_cb(struct timeval *tv)
{
    ESP_LOGI(TAG, "Notification of a time synchronization event");
}

static void print_servers(void)
{
    ESP_LOGI(TAG, "List of configured NTP servers:");

    for (uint8_t i = 0; i < SNTP_MAX_SERVERS; ++i){
        if (esp_sntp_getservername(i)){
            ESP_LOGI(TAG, "server %d: %s", i, esp_sntp_getservername(i));
        } else {
            // we have either IPv4 or IPv6 address, let's print it
            char buff[INET6_ADDRSTRLEN];
            ip_addr_t const *ip = esp_sntp_getserver(i);
            if (ipaddr_ntoa_r(ip, buff, INET6_ADDRSTRLEN) != NULL)
                ESP_LOGI(TAG, "server %d: %s", i, buff);
        }
    }
}

/**
 * @brief 获取时间
 * 
 */
static void obtain_time(void)
{
#if LWIP_DHCP_GET_NTP_SRV
    /**
     * NTP server address could be acquired via DHCP,
     * see following menuconfig options:
     * 'LWIP_DHCP_GET_NTP_SRV' - enable STNP over DHCP
     * 'LWIP_SNTP_DEBUG' - enable debugging messages
     *
     * NOTE: This call should be made BEFORE esp acquires IP address from DHCP,
     * otherwise NTP option would be rejected by default.
     */
    ESP_LOGI(TAG, "Initializing SNTP");
    esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG(CONFIG_SNTP_TIME_SERVER);
    config.start = false;                       // start SNTP service explicitly (after connecting)
    config.server_from_dhcp = true;             // accept NTP offers from DHCP server, if any (need to enable *before* connecting)
    config.renew_servers_after_new_IP = true;   // let esp-netif update configured SNTP server(s) after receiving DHCP lease
    config.index_of_first_server = 1;           // updates from server num 1, leaving server 0 (from DHCP) intact
    // configure the event on which we renew servers
#ifdef CONFIG_EXAMPLE_CONNECT_WIFI
    config.ip_event_to_renew = IP_EVENT_STA_GOT_IP;
#else
    config.ip_event_to_renew = IP_EVENT_ETH_GOT_IP;
#endif
    config.sync_cb = time_sync_notification_cb; // only if we need the notification function
    esp_netif_sntp_init(&config);

#endif /* LWIP_DHCP_GET_NTP_SRV */

#if LWIP_DHCP_GET_NTP_SRV
    ESP_LOGI(TAG, "Starting SNTP");
    esp_netif_sntp_start();
#if LWIP_IPV6 && SNTP_MAX_SERVERS > 2
    /* This demonstrates using IPv6 address as an additional SNTP server
     * (statically assigned IPv6 address is also possible)
     */
    ip_addr_t ip6;
    if (ipaddr_aton("2a01:3f7::1", &ip6)) {    // ipv6 ntp source "ntp.netnod.se"
        esp_sntp_setserver(2, &ip6);
    }
#endif  /* LWIP_IPV6 */

#else
    ESP_LOGI(TAG, "Initializing and starting SNTP");
#if CONFIG_LWIP_SNTP_MAX_SERVERS > 1
    /* This demonstrates configuring more than one server
     */
    esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG_MULTIPLE(2,
                               ESP_SNTP_SERVER_LIST(CONFIG_SNTP_TIME_SERVER, "pool.ntp.org" ) );
#else
    /*
     * This is the basic default config with one server and starting the service
     */
    esp_sntp_config_t config = ESP_NETIF_SNTP_DEFAULT_CONFIG("ntp.aliyun.com");
#endif
    config.sync_cb = time_sync_notification_cb;     // Note: This is only needed if we want
#ifdef CONFIG_SNTP_TIME_SYNC_METHOD_SMOOTH
    config.smooth_sync = true;
#endif

    esp_netif_sntp_init(&config);
#endif

    print_servers();

    // 主LED显示NTP同步中状态
    led_indicator_start(led_handle, BLINK_NTP_SYNCING);

    // wait for time to be set
    time_t now = 0;
    struct tm timeinfo = { 0 };

    ESP_LOGI(TAG, "Waiting for system time to be set... ");
    while (esp_netif_sntp_sync_wait(2000 / portTICK_PERIOD_MS) == ESP_ERR_TIMEOUT) {
        // 继续显示NTP同步中状态
    }
    ESP_LOGI(TAG, "Time set");

    time(&now);
    localtime_r(&now, &timeinfo);
    ESP_LOGI(TAG, "Time set: %d-%d-%d %d:%d:%d", timeinfo.tm_year+1900, timeinfo.tm_mon+1, timeinfo.tm_mday, timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec);
    
    // 停止NTP同步中状态，显示同步完成
    led_indicator_stop(led_handle, BLINK_NTP_SYNCING);
    led_indicator_start(led_handle, BLINK_NTP_SYNC_DONE);
    
    // 等待同步完成指示结束
    vTaskDelay(pdMS_TO_TICKS(1000));
    
    // esp_netif_sntp_deinit();
}

static esp_err_t esp_storage_init(void)
{
    esp_err_t ret = nvs_flash_init();

    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
        // NVS partition was truncated and needs to be erased
        // Retry nvs_flash_init
        ESP_ERROR_CHECK(nvs_flash_erase());
        ret = nvs_flash_init();
    }

    return ret;
}

/**
 * @brief 初始化LED指示器
 */
static esp_err_t init_led_indicator(void)
{
    // GPIO配置 - LED1 (主状态指示 - WiFi和NTP状态)
    led_indicator_gpio_config_t gpio_config_1 = {
        .gpio_num = BOARD_IO_LED_1,
        .is_active_level_high = true,  // 根据实际硬件调整
    };

    // GPIO配置 - LED2 (DS1302芯片1状态)
    led_indicator_gpio_config_t gpio_config_2 = {
        .gpio_num = BOARD_IO_LED_2,
        .is_active_level_high = true,  // 根据实际硬件调整
    };

    // GPIO配置 - LED3 (DS1302芯片2状态)
    led_indicator_gpio_config_t gpio_config_3 = {
        .gpio_num = BOARD_IO_LED_3,
        .is_active_level_high = true,  // 根据实际硬件调整
    };

    // GPIO配置 - LED4 (DS1302芯片3状态)
    led_indicator_gpio_config_t gpio_config_4 = {
        .gpio_num = BOARD_IO_LED_4,
        .is_active_level_high = true,  // 根据实际硬件调整
    };

    // LED指示器配置
    const led_indicator_config_t config = {
        .blink_lists = led_mode,
        .blink_list_num = BLINK_MAX,
    };
    
    // 创建主LED指示器
    esp_err_t ret = led_indicator_new_gpio_device(&config, &gpio_config_1, &led_handle);
    if (ret != ESP_OK || led_handle == NULL) {
        ESP_LOGE(TAG, "Failed to create main LED indicator, ret: %s", esp_err_to_name(ret));
        return ESP_FAIL;
    }
    
    // 创建LED2指示器 (DS1302芯片1)
    ret = led_indicator_new_gpio_device(&config, &gpio_config_2, &led_handle_2);
    if (ret != ESP_OK || led_handle_2 == NULL) {
        ESP_LOGE(TAG, "Failed to create LED2 indicator, ret: %s", esp_err_to_name(ret));
        return ESP_FAIL;
    }
    
    // 创建LED3指示器 (DS1302芯片2)
    ret = led_indicator_new_gpio_device(&config, &gpio_config_3, &led_handle_3);
    if (ret != ESP_OK || led_handle_3 == NULL) {
        ESP_LOGE(TAG, "Failed to create LED3 indicator, ret: %s", esp_err_to_name(ret));
        return ESP_FAIL;
    }
    
    // 创建LED4指示器 (DS1302芯片3)
    ret = led_indicator_new_gpio_device(&config, &gpio_config_4, &led_handle_4);
    if (ret != ESP_OK || led_handle_4 == NULL) {
        ESP_LOGE(TAG, "Failed to create LED4 indicator, ret: %s", esp_err_to_name(ret));
        return ESP_FAIL;
    }
    
    ESP_LOGI(TAG, "All LED indicators initialized successfully");
    return ESP_OK;
}

/**
 * @brief 从系统时间同步所有DS1302芯片
 */
static void sync_time_to_all_ds1302(void)
{
    if (sync_in_progress) {
        ESP_LOGW(TAG, "Time sync already in progress, ignoring button press");
        return;
    }
    
    sync_in_progress = true;
    sync_status = SYNC_STATUS_SYNCING;
    
    ESP_LOGI(TAG, "Button pressed - starting time sync for all DS1302 chips");
    
    // 获取当前系统时间
    time_t now;
    struct tm timeinfo;
    time(&now);
    localtime_r(&now, &timeinfo);
    
    ESP_LOGI(TAG, "Syncing time to all DS1302 chips: %d-%d-%d %d:%d:%d",
             timeinfo.tm_year + 1900, timeinfo.tm_mon + 1, timeinfo.tm_mday,
             timeinfo.tm_hour, timeinfo.tm_min, timeinfo.tm_sec);
    
    // 先关闭所有状态LED
    led_indicator_stop(led_handle_2, BLINK_CHIP_SUCCESS);
    led_indicator_stop(led_handle_2, BLINK_CHIP_FAILED);
    led_indicator_stop(led_handle_3, BLINK_CHIP_SUCCESS);
    led_indicator_stop(led_handle_3, BLINK_CHIP_FAILED);
    led_indicator_stop(led_handle_4, BLINK_CHIP_SUCCESS);
    led_indicator_stop(led_handle_4, BLINK_CHIP_FAILED);
    
    led_indicator_start(led_handle_2, BLINK_CHIP_SYNC_START);
    led_indicator_start(led_handle_3, BLINK_CHIP_SYNC_START);
    led_indicator_start(led_handle_4, BLINK_CHIP_SYNC_START);

    bool all_success = true;
    int failed_chips[3] = {0,0,0};

    // 依次对每个DS1302芯片进行校时
    for (int i = 0; i < 3; i++) {
        int err = ESP_OK;
        ESP_LOGI(TAG, "Syncing DS1302 chip %d ...", i + 1);

        // 启动DS1302芯片
        err = ds1302_start(&ds1302_dev[i], true);
        if (err != ESP_OK) {
            ESP_LOGE(TAG, "Failed to start DS1302 chip %d, err=%s", i + 1, esp_err_to_name(err));
            all_success = false;
            failed_chips[i] = 1;
            // 对应LED快闪表示失败
            if (i == 0) {
                led_indicator_start(led_handle_2, BLINK_CHIP_FAILED);
            } else if (i == 1) {
                led_indicator_start(led_handle_3, BLINK_CHIP_FAILED);
            } else if (i == 2) {
                led_indicator_start(led_handle_4, BLINK_CHIP_FAILED);
            }
            continue;
        }
        vTaskDelay(pdMS_TO_TICKS(10));
        
        // 检测DS1302芯片状态
        bool running = false;
        err = ds1302_is_running(&ds1302_dev[i], &running);
        if (err == ESP_OK && running) {
            ESP_LOGI(TAG, "DS1302 chip %d: DETECTED & RUNNING", i + 1);
        } else if (err == ESP_OK) {
            ESP_LOGW(TAG, "DS1302 chip %d: DETECTED but STOPPED", i + 1);
            all_success = false;
            failed_chips[i] = 1;
            // 对应LED快闪表示失败
            if (i == 0) {
                led_indicator_start(led_handle_2, BLINK_CHIP_FAILED);
            } else if (i == 1) {
                led_indicator_start(led_handle_3, BLINK_CHIP_FAILED);
            } else if (i == 2) {
                led_indicator_start(led_handle_4, BLINK_CHIP_FAILED);
            }
            continue;
        } else {
            ESP_LOGE(TAG, "DS1302 chip %d: NOT DETECTED (err=%s)", i + 1, esp_err_to_name(err));
            all_success = false;
            failed_chips[i] = 1;
            // 对应LED快闪表示失败
            if (i == 0) {
                led_indicator_start(led_handle_2, BLINK_CHIP_FAILED);
            } else if (i == 1) {
                led_indicator_start(led_handle_3, BLINK_CHIP_FAILED);
            } else if (i == 2) {
                led_indicator_start(led_handle_4, BLINK_CHIP_FAILED);
            }
            continue;
        }
        vTaskDelay(pdMS_TO_TICKS(10));
        
        // 写入当前时间
        err = ds1302_set_time(&ds1302_dev[i], &timeinfo);
        if (err == ESP_OK) {
            ESP_LOGI(TAG, "Successfully synced time to DS1302 chip %d", i + 1);
            failed_chips[i] = 0;
            // 对应LED常亮表示成功
            if (i == 0) {
                led_indicator_start(led_handle_2, BLINK_CHIP_SUCCESS);
            } else if (i == 1) {
                led_indicator_start(led_handle_3, BLINK_CHIP_SUCCESS);
            } else if (i == 2) {
                led_indicator_start(led_handle_4, BLINK_CHIP_SUCCESS);
            }
        } else {
            ESP_LOGE(TAG, "Failed to sync time to DS1302 chip %d, err=%s", i + 1, esp_err_to_name(err));
            all_success = false;
            failed_chips[i] = 1;
            // 对应LED快闪表示失败
            if (i == 0) {
                led_indicator_start(led_handle_2, BLINK_CHIP_FAILED);
            } else if (i == 1) {
                led_indicator_start(led_handle_3, BLINK_CHIP_FAILED);
            } else if (i == 2) {
                led_indicator_start(led_handle_4, BLINK_CHIP_FAILED);
            }
            continue;
        }
        vTaskDelay(pdMS_TO_TICKS(10));
        
        // 读取DS1302芯片时间，判断年月日是否正确
        struct tm ds_time;
        err = ds1302_get_time(&ds1302_dev[i], &ds_time);
        if (err == ESP_OK) {
            // 检查年份、月份、日期是否有效
            if (ds_time.tm_year != timeinfo.tm_year ||    // 2000~2100年
                ds_time.tm_mon != timeinfo.tm_mon ||         // 月份范围0~11
                ds_time.tm_mday != timeinfo.tm_mday) {       // 日期范围1~31
                ESP_LOGW(TAG, "DS1302 chip %d: 日期异常，读取到的时间为 %d-%d-%d %d:%d:%d",
                         i + 1, ds_time.tm_year + 1900, ds_time.tm_mon + 1, ds_time.tm_mday,
                         ds_time.tm_hour, ds_time.tm_min, ds_time.tm_sec);
                all_success = false;
                failed_chips[i] = 1;
                // 停止成功指示，改为失败指示
                if (i == 0) {
                    led_indicator_stop(led_handle_2, BLINK_CHIP_SUCCESS);
                    led_indicator_start(led_handle_2, BLINK_CHIP_FAILED);
                } else if (i == 1) {
                    led_indicator_stop(led_handle_3, BLINK_CHIP_SUCCESS);
                    led_indicator_start(led_handle_3, BLINK_CHIP_FAILED);
                } else if (i == 2) {
                    led_indicator_stop(led_handle_4, BLINK_CHIP_SUCCESS);
                    led_indicator_start(led_handle_4, BLINK_CHIP_FAILED);
                }
            } else {
                ESP_LOGI(TAG, "DS1302 chip %d: 当前时间为 %d-%d-%d %d:%d:%d",
                         i + 1, ds_time.tm_year + 1900, ds_time.tm_mon + 1, ds_time.tm_mday,
                         ds_time.tm_hour, ds_time.tm_min, ds_time.tm_sec);
                failed_chips[i] = 0;
                // 保持LED常亮表示成功
            }
        } else {
            ESP_LOGE(TAG, "读取DS1302 chip %d 时间失败, err=%s", i + 1, esp_err_to_name(err));
            all_success = false;
            failed_chips[i] = 1;
            // 停止成功指示，改为失败指示
            if (i == 0) {
                led_indicator_stop(led_handle_2, BLINK_CHIP_SUCCESS);
                led_indicator_start(led_handle_2, BLINK_CHIP_FAILED);
            } else if (i == 1) {
                led_indicator_stop(led_handle_3, BLINK_CHIP_SUCCESS);
                led_indicator_start(led_handle_3, BLINK_CHIP_FAILED);
            } else if (i == 2) {
                led_indicator_stop(led_handle_4, BLINK_CHIP_SUCCESS);
                led_indicator_start(led_handle_4, BLINK_CHIP_FAILED);
            }
        }
        // 短暂延时，避免过快操作
        vTaskDelay(pdMS_TO_TICKS(100));
    }
    
    vTaskDelay(pdMS_TO_TICKS(1000));
    
    // 关闭DS1302芯片
    ds1302_set_clk_io(&ds1302_dev[0], 1);
    ds1302_set_clk_io(&ds1302_dev[1], 1);
    ds1302_set_clk_io(&ds1302_dev[2], 1);

    // 根据结果设置状态和主LED指示
    if (all_success) {
        sync_status = SYNC_STATUS_SUCCESS;
        ESP_LOGI(TAG, "All DS1302 chips synced successfully");
            
        // 保持3个状态LED常亮2秒，然后熄灭
        vTaskDelay(pdMS_TO_TICKS(2000));
        led_indicator_stop(led_handle_2, BLINK_CHIP_SUCCESS);
        led_indicator_stop(led_handle_3, BLINK_CHIP_SUCCESS);
        led_indicator_stop(led_handle_4, BLINK_CHIP_SUCCESS);
    } else {
        sync_status = SYNC_STATUS_FAILED;
        ESP_LOGE(TAG, "Time sync failed chips: %d, %d, %d", failed_chips[0], failed_chips[1], failed_chips[2]);
        
        // 保持失败的状态LED闪烁，直到下次校时
        // 成功的LED保持常亮状态
    }
    
    sync_in_progress = false;
}

/**
 * @brief 校时任务处理函数
 */
static void sync_task_handler(void *pvParameters)
{
    sync_task_msg_t msg;
    
    ESP_LOGI(TAG, "Sync task started");
    
    while (1) {
        // 等待消息
        if (xQueueReceive(sync_queue, &msg, portMAX_DELAY) == pdTRUE) {
            if (msg.trigger_sync) {
                ESP_LOGI(TAG, "Received sync request in task");
                sync_time_to_all_ds1302();
            }
        }
    }
}

/**
 * @brief 按键单击回调函数
 */
static void button_single_click_cb(void *hardware_data, void *usr_data)
{
    ESP_LOGI(TAG, "BTN: BUTTON_SINGLE_CLICK - Sending sync request to task");
    
    // 发送校时请求到任务
    sync_task_msg_t msg = {
        .trigger_sync = true
    };
    
    if (xQueueSend(sync_queue, &msg, pdMS_TO_TICKS(100)) != pdTRUE) {
        ESP_LOGE(TAG, "Failed to send sync request to task");
    }
}

/**
 * @brief 按键释放回调函数
 */
static void button_press_up_cb(void *hardware_data, void *usr_data)
{
    ESP_LOGI(TAG, "BTN: BUTTON_PRESS_UP");
}

/**
 * @brief 按键重复按下回调函数
 */
static void button_press_repeat_cb(void *hardware_data, void *usr_data)
{
    uint8_t press_repeat = iot_button_get_repeat((button_handle_t)hardware_data);
    ESP_LOGI(TAG, "BTN: BUTTON_PRESS_REPEAT[%d]", press_repeat);
}

/**
 * @brief 按键长按开始回调函数
 */
static void button_long_press_start_cb(void *hardware_data, void *usr_data)
{
    ESP_LOGI(TAG, "BTN: BUTTON_LONG_PRESS_START");
}

bool got_ip = false;
static void ip_event_sta_got_ip_handler(void *arg, esp_event_base_t event_base,
    int32_t event_id, void *event_data)
{
    ip_event_got_ip_t *event = (ip_event_got_ip_t*)event_data;
    ESP_LOGI(TAG, "Connected with IP Address:" IPSTR, IP2STR(&event->ip_info.ip));

    got_ip = true;
}

void app_main(void)
{
    
    setenv("TZ", "CST-8", 1);
    tzset();

    esp_log_level_set("*", ESP_LOG_WARN);
    esp_log_level_set(TAG, ESP_LOG_INFO);

    esp_storage_init();

    ESP_ERROR_CHECK(esp_netif_init());
    ESP_ERROR_CHECK(esp_event_loop_create_default());

    esp_bridge_create_all_netif();
    ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT, IP_EVENT_STA_GOT_IP, &ip_event_sta_got_ip_handler, NULL, NULL));  

#if defined(CONFIG_BRIDGE_DATA_FORWARDING_NETIF_SOFTAP)
    wifi_config_t wifi_cfg = {
        .ap = {
            .ssid = CONFIG_BRIDGE_SOFTAP_SSID,
            .password = CONFIG_BRIDGE_SOFTAP_PASSWORD,
        }
    };
    esp_bridge_wifi_set_config(WIFI_IF_AP, &wifi_cfg);
#endif
#if defined(CONFIG_BRIDGE_EXTERNAL_NETIF_STATION)
    esp_wifi_connect();
#endif

    iot_board_init();

    // 初始化LED指示器
    if (init_led_indicator() != ESP_OK) {
        ESP_LOGE(TAG, "Failed to initialize LED indicator");
        return;
    }

    // 创建校时任务队列
    sync_queue = xQueueCreate(5, sizeof(sync_task_msg_t));
    if (sync_queue == NULL) {
        ESP_LOGE(TAG, "Failed to create sync queue");
        return;
    }

    // 创建校时任务
    BaseType_t ret = xTaskCreate(sync_task_handler, "sync_task", SYNC_TASK_STACK_SIZE, 
                                 NULL, SYNC_TASK_PRIORITY, &sync_task_handle);
    if (ret != pdPASS) {
        ESP_LOGE(TAG, "Failed to create sync task");
        return;
    }

    // 注册按键回调函数
    iot_board_button_register_cb(BOARD_IO_BUTTON_1, BUTTON_PRESS_DOWN, button_single_click_cb);

#if defined(CONFIG_APP_BRIDGE_USE_WEB_SERVER)
    StartWebServer();
#endif /* CONFIG_APP_BRIDGE_USE_WEB_SERVER */
#if defined(CONFIG_APP_BRIDGE_USE_WIFI_PROVISIONING_OVER_BLE)
    esp_bridge_wifi_prov_mgr();
#endif /* CONFIG_APP_BRIDGE_USE_WIFI_PROVISIONING_OVER_BLE */
    
    // 主LED显示WiFi连接中状态
    led_indicator_start(led_handle, BLINK_WIFI_CONNECTING);
    
    // 等待WiFi连接
    while(got_ip==false){
        vTaskDelay(pdMS_TO_TICKS(100));
    }
    
    // WiFi连接成功，主LED显示已连接状态
    led_indicator_stop(led_handle, BLINK_WIFI_CONNECTING);
    led_indicator_start(led_handle, BLINK_WIFI_CONNECTED);
    
    /* 获取NTP时间 */
    obtain_time();
    
    // NTP同步完成后，主LED熄灭
    led_indicator_stop(led_handle, BLINK_WIFI_CONNECTED);

    /* 初始化DS1302 1*/
    ds1302_dev[0].ce_pin = BOARD_IO_DS1302_1_CE;
    ds1302_dev[0].sclk_pin = BOARD_IO_DS1302_1_CLK;
    ds1302_dev[0].io_pin = BOARD_IO_DS1302_1_DATA;
    ESP_ERROR_CHECK(ds1302_init(&ds1302_dev[0]));

    /* 初始化DS1302 2*/
    ds1302_dev[1].ce_pin = BOARD_IO_DS1302_2_CE;
    ds1302_dev[1].sclk_pin = BOARD_IO_DS1302_2_CLK;
    ds1302_dev[1].io_pin = BOARD_IO_DS1302_2_DATA;
    ESP_ERROR_CHECK(ds1302_init(&ds1302_dev[1]));

    /* 初始化DS1302 3*/
    ds1302_dev[2].ce_pin = BOARD_IO_DS1302_3_CE;
    ds1302_dev[2].sclk_pin = BOARD_IO_DS1302_3_CLK;
    ds1302_dev[2].io_pin = BOARD_IO_DS1302_3_DATA;
    ESP_ERROR_CHECK(ds1302_init(&ds1302_dev[2]));
    
    ESP_LOGI(TAG, "System initialized. Press button to sync time to all DS1302 chips.");
    
    // 系统就绪，所有状态LED快速闪烁一次表示准备就绪
    led_indicator_start(led_handle_2, BLINK_CHIP_FAILED);
    led_indicator_start(led_handle_3, BLINK_CHIP_FAILED);
    led_indicator_start(led_handle_4, BLINK_CHIP_FAILED);
    vTaskDelay(pdMS_TO_TICKS(500));  // 闪烁0.5秒
    led_indicator_stop(led_handle_2, BLINK_CHIP_FAILED);
    led_indicator_stop(led_handle_3, BLINK_CHIP_FAILED);
    led_indicator_stop(led_handle_4, BLINK_CHIP_FAILED);
    
    // 主循环
    while (1) {
        vTaskDelay(pdMS_TO_TICKS(1000));
    }
}
